/**
 * axios统一包装工具
 */

import axios from "axios";
import router from "@/router";

//创建一个axios对象，设置基本的请求路径为http://172.27.181.31:88
const request = axios.create({
    baseURL: 'http://localhost:88',
    timeout: 30000
})

//配置axios请求拦截器
request.interceptors.request.use(
    config => {
        config.headers['Content-Type'] = 'application/json;charset=utf-8';
        //从本地存储中获取token
        let user = localStorage.getItem("user")
        //设置token
        if (user) {
            user = JSON.parse(user)
            config.headers['Authorization'] = 'Bearer ' + user.data.token
        }

        return config
    },
    error => {
        console.error('request error:' + error)
        return Promise.reject(error)
    }
)

//配置axios响应拦截器
request.interceptors.response.use(
    response => {
        //当用户试图直接访问数据且没有登录过或者token无效时，直接跳回登录页
        if (response.data.code === 401) {
            localStorage.clear()
            router.push('/login')
        }
        //当用户试图访问数据且没有权限时，不允许跳转
        if (response.data.code === 403) {
            const path = router.currentRoute.fullPath
            if (path.startsWith('/admin')) {
                router.push('/clientView')
            } else {
                router.push('/adminView')
            }
        }
        return response
    },
    error => {
        console.error('request error:' + error)
        return Promise.reject(error)
    }
)

export default request
